<?php

namespace App\Models\OperationManagement;

use App\Models\CarModels\CarCity;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;

class SanitationToilet extends Model
{
    use SoftDeletes;
    use SpatialTrait;
    protected $guarded = [];
    protected $spatialFields = ['location'];

    //查询list
    public function getList($request)
    {
    	$per_page = $request->input('per_page',10);
    	return self::orderBy('id','desc')
                ->with(['areas.city','employees'])
                ->where(function($query) use ($request){
                    //检测当前的请求中是否包含name、type参数
                    $name = $request->input('name', '');//公厕名称
                    $principal_id = $request->input('principal_id','');//区负责人
                    $area_id = $request->input('area_id','');//区域
                    $location = $request->input('location','');
                    if(!empty($name)) {
                        $query->where('name','like','%'.$name.'%');
                    }
                    if(!empty($principal_id)) {
                        $query->where('principal_id','=',$principal_id);
                    }
                    if(!empty($area_id)) {
                        $query->where('area_id','=',$area_id);
                    }
                    if(!empty($location)) {
                        $location = Point::fromString($location);
                        $query->distance('location', $location, 10);
                    }
                })
                ->paginate($per_page)->toArray();
    }

    //查询城市、区域
    public function areas()
    {
        return $this->belongsTo(\App\Models\CarModels\CarArea::class,'area_id','id')->select('id','name','city_id');
    }

    //查看负责人
    public function employees()
    {
        return $this->belongsTo(\App\Models\SystemManagement\Employee::class,'principal_id','id')->select('id','name');
    }
}
